package com.lagou.edu.dao.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.lagou.edu.annotation.MiniAutoWired;
import com.lagou.edu.annotation.MiniRepository;
import com.lagou.edu.dao.IAccountDao;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.service.ITransferService;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.DruidUtils;
import org.junit.Test;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName: JdbcAccountCardNo
 * @Auther: Jerry
 * @Date: 2020/6/29 10:42
 * @Desctiption: TODO
 * @Version: 1.0
 */
@MiniRepository("accountDao")
public class JdbcIAccountDaoImpl implements IAccountDao {

    private ConnectionUtils connectionUtils = ConnectionUtils.newInstance();

    @Override
    public Account getAccountByCardNo(String cardNo) throws SQLException {
        // 获取连接
        Connection conn = connectionUtils.getCurrentThreadConn();
        // sql语句
        String sql = "select name, card_no, money from account where card_no = ?";
        // 获取预处理对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // 设置参数
        pstmt.setString(1, cardNo);
        // 执行sql语句
        pstmt.execute();

        ResultSet resultSet = pstmt.getResultSet();
        Account account = new Account();
        while (resultSet.next()){
            account.setName(resultSet.getString("name"));
            account.setCardNo(resultSet.getString("card_no"));
            account.setMoney(resultSet.getBigDecimal("money"));
        }

        // 关闭资源
        resultSet.close();
        pstmt.close();
//        conn.close();

        return account;
    }

    @Override
    public int updateAccountByCardNo(Account account) throws SQLException {
        // 获取连接
        Connection conn = connectionUtils.getCurrentThreadConn();

        // sql语句
        String sql = "update account set money = ? where card_no = ?";
        // 获取预处理对象
        PreparedStatement pstmt = conn.prepareStatement(sql);
        // 设置参数
        pstmt.setBigDecimal(1, account.getMoney());
        pstmt.setString(2, account.getCardNo());
        // 执行sql语句
        pstmt.execute();

        int updateCount = pstmt.getUpdateCount();

        // 关闭资源
        pstmt.close();
//        conn.close();
        return updateCount;
    }

}
